import React, { Component } from 'react';

import {
	View,
	Text,
	StyleSheet
} from 'react-native';
import { GLOBAL } from '../config/global';
import WS from "../utils/websocket";
import { NavigationEvents } from 'react-navigation';
const scale = GLOBAL.SCALE;
export class WebSocketPage extends Component {

	constructor(props) {
		super(props);

		this.state = {
			//	wsState: WSConnectType && WSConnectType()
		}
	}

	componentWillMount = () => {
		//WS.createWebSocket({ name: "zy" });
	}

	_open = () => {
		WSCreate && WSCreate();
		WS.onopen = () => {
			console.log("连接成功了");
			this.setState({
				wsState: WSConnectType()
			})
		}

		WS.onmessage = function (event) {
			console.log("1223", event)
		}
		WS.onclose = () => {
			console.log("关闭监听");
			this.setState({
				wsState: WSConnectType()
			})
		}
	}

	_close = () => {
		WS.close();
	}

	_send = () => {
		WS.send("发的第一条消息");
	}




	render() {
		let { wsState } = this.state
		return <View>
			<NavigationEvents
				onWillFocus={({ action }) => {
					if (WS) {
						WS.onclose = () => {
							console.log("关闭监听---22");
							this.setState({
								wsState: WSConnectType()
							})
						}
					}
				}}
				onWillBlur={async ({ action }) => {
				}}
			/>
			<Text>状态:{wsState}</Text>
			<View style={{ flexDirection: 'row', justifyContent: 'space-around', marginTop: 30 * scale }}>
				<Text onPress={this._open}>打开</Text>
				<Text onPress={this._send}>发消息</Text>
				<Text onPress={this._close}>关闭</Text>
			</View>
		</View>
	}

}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		position: 'relative',
		backgroundColor: '#000'
		//paddingBottom: 30 * scale
	},
})